#include "EventLoopThreadPool.h"
#include "EventLoopThread.h"
#include <memory>
class EventLoop;

EventLoopThreadPool::EventLoopThreadPool(EventLoop *baseLoop, const std::string &nameArg) 
    : baseLoop_(baseLoop)
    , name_(nameArg)
    , started_(false)
    , numThreads_(0)
    , next_(0)
{}

EventLoopThreadPool::~EventLoopThreadPool() { 
    //不用析构，因为eventloop都是栈上的资源
}

        
void EventLoopThreadPool::start(const ThreadInitCallback &cb) {
    started_ = true;

    for (int i = 0; i < numThreads_; ++i) {
        char buf[name_.size() + 32];
        snprintf(buf, sizeof buf, "%s%d", name_.c_str(), i); //线程名字
        
        EventLoopThread *t = new EventLoopThread(cb, buf);
        threads_.push_back(std::unique_ptr<EventLoopThread>(t)); // 把t转化为智能指针，不需要手动管理堆对象
        loops_.push_back(t->startLoop()); // 底层创建线程 绑定eventloop（栈对象）并返回eventloop地址
    }
    if (numThreads_ == 0 && cb) {//只有mainloop
        cb(baseLoop_);
    }
}

// 如果工作在多线程中，baseLoop_会默认以轮询的方式分配channel给subloop
EventLoop* EventLoopThreadPool::getNextLoop() {
    EventLoop *loop = baseLoop_;
    if (!loops_.empty()) { // 通过轮询， 获取下一个处理事件的loop
        loop = loops_[next_];
        ++next_;
        if (next_ >= loops_.size()) {
            next_ = 0;
        }
    }
    return loop;
}
        
std::vector<EventLoop*> EventLoopThreadPool::getAllLoops() {
    if (loops_.empty()) {
        return std::vector<EventLoop *> (1, baseLoop_);
    } else {
        return loops_;
    }
    
}
        
       